/**
 * 
 * The controller of the secretary
 * @returns {Controller_Secretary}
 */
function Controller_Secretary()
{
    /**
     * Communication with Server
     * @returns {undefined}
     */
    this.autoGetUpdatesFromServer = function()
    {
        var checkmsg = function()
        {
            CPS.sendRequestToServer("CPS_CheckServerNotification", [CPS.getUserID()], function(data) {
                var len = data.Response_CarriedData.length;
                if (len < 1)
                {
                    return;
                } else {
                    // show the message
                    for (var i = 0; i < len; i++) {
                        CPS.showNotification("[" + (i + 1) + "]:" + data.Response_CarriedData[i].MessageTitle, data.Response_CarriedData[i].MessageContent, 2, 60000);
                    }
                    currentController.initLeftBar();
                }

            });
        };

        window.setInterval(checkmsg, 3000);
    };
    /**
     * 
     * @returns {undefined}
     */
    this.initLeftBar = function()
    {
        CPS.ShowProcessing();
        var parentContainerSelector = "#Index_West";
        $(parentContainerSelector).html("").append("<div id='Accordion_Left'></div>");
        var accordionSelector = String.format("{0} {1}", parentContainerSelector, " #Accordion_Left");
        $(accordionSelector).accordion({animate: true}); // init the accordinon
        // send request to get Data From DBs
        CPS.sendRequestToServer("Secretaty_QuerySummary", [CPS.getSchoolID()], function(data) {
            if (data.Response_CarriedData.length < 1)
            {
                CPS.CloseProcessing(function() {

                });
                return;
            }
            $(accordionSelector).accordion('add', {
                title: data.Response_CarriedData[0].HandleSchoolName,
                id: CPS.getSchoolID(),
                collapsible: true,
                selected: false
            }).accordion({
                onSelect: function(title, index)
                {
                    var innerHtml = "<table style='min-width:100px'>";
                    var objData = data.Response_CarriedData;
                    for (var id in objData) {
                        var appTypeId = objData[id].ApplicationTypeID;
                        var appTypeName = objData[id].ApplicationTypeName;
                        var schoolID = objData[id].SchoolID;
                        var schoolName = objData[id].HandleSchoolName;
                        var count = objData[id].RecordCount;
                        innerHtml += String.format("<tr><td>{0}</td>", appTypeName);
                        var strShowDetialHtml = "<td style='text-align:right'>[<a href='#' onClick='currentController.ViewAccordionDetail(\"{0}\",\"{1}\",\"{2}\",\"{3}\")'>{4}</a>]</td></tr>";
                        innerHtml += String.format(strShowDetialHtml, schoolID, schoolName, appTypeId, appTypeName, count);
                    }
                    innerHtml += "</table>";
                    $(accordionSelector).accordion('getPanel', index).panel({
                        collapsible: true,
                        content: innerHtml
                    });
                }
            });
            CPS.CloseProcessing(function() {

            });
        });
    };

    /**
     * View the Detail while click the accordion
     * @param {type} schoolID
     * @param {type} schoolName
     * @param {type} appTypeId
     * @param {type} appTypeName
     * @returns {undefined}
     */
    this.ViewAccordionDetail = function(schoolID, schoolName, appTypeId, appTypeName)
    {
        CPS.ShowProcessing();
        var title = String.format("{0}-[{1}]", schoolName, appTypeName);
        var selectedPanel = CPS.addnewTab(title);
        var panelSelector = "#" + selectedPanel.innerDivID;
        $(panelSelector).html("");   // remove all the old one

        var strAction = "ViewAccordionDetail|{0}|{1}|{2}|{3}";
        strAction = String.format(strAction, schoolID, schoolName, appTypeId, appTypeName);
        // set to the hidden action value    
        $(selectedPanel.paramSelector).val(strAction);

        var rowFormatter = function(value, rowData, rowindex) {
            var currentStatus = rowData.ApplicationStateID;
            // Accept button
            if ((currentStatus === "F01")) {
                var html = "<button id='Item_Btn_Accept'onClick ='currentController.Application_Item_Accept(\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\");'>Accept</button>";
                html = String.format(html, rowData.ApplicationId, rowData.HandleSchoolID, rowData.ApplicationStateID, rowData.ActionUserID, strAction);
                return html;
            }

            // the assign 
            if (currentStatus === "S01") {
                var html = "<button id='Item_Btn_Assign' onClick ='currentController.Application_Item_Assign(\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\");'>Assign</button>";
                html = String.format(html, rowData.ApplicationId, rowData.HandleSchoolID, rowData.ApplicationStateID, rowData.ActionUserID, strAction);
                return html;
            }
        };
        var fontStyler = function() {
            return "font-size:14px;";
        };

        var conditionStyler = function(value, row, index) {
            if (value > CPS.getSystemSetting("ElaspeDayAlarm")) {
                return 'color:red;font-size:18px;text-align:center;text;font-weight: bold;';
            } else
            {
                return 'font-size:14px;text-align:center';
            }
        };

        var header = [[
                {field: 'ApplicationId', title: 'ApplicationId', hidden: true},
                {field: 'ApplicationTypeID', title: 'ApplicationTypeID', hidden: true},
                {field: 'RefferenceTypeID', title: 'RefferenceTypeID', hidden: true},
                {field: 'LatestComment', title: 'LatestComment', hidden: true},
                {field: 'HandleSchoolID', title: 'HandleSchoolID', hidden: true},
                {field: 'HandleSchoolName', title: 'HandleSchoolName', hidden: true},
                {field: 'SecretaryID', title: 'SecretatyID', hidden: true},
                {field: 'SecretaryName', title: 'SecretatyName', hidden: true},
                {field: 'SecretaryEmail', title: 'SecretatyEmail', hidden: true},
                {field: 'AdvisorID', title: 'AdvisorID', hidden: true},
                {field: 'AdvisorName', title: 'AdvisorName', hidden: true},
                {field: 'AdvisorEmail', title: 'AdvisorEmail', hidden: true},
                {field: 'ActionUserID', title: 'ActionUserID', hidden: true},
                {field: 'ActionUserName', title: 'ActionUserName', hidden: true},
                {field: 'ActionUserEmail', title: 'ActionUserEmail', hidden: true},
                {field: 'SortIndex', title: 'SortIndex', hidden: true},
                {field: 'LastUpdateTime', title: 'LastUpdateTime', width: 90, hidden: true},
                //not hidden
                {field: 'ApplicationTypeName', title: 'Application Type', width: 106, sortable: true, styler: fontStyler},
                {field: 'RefferenceUserName', title: 'Student Name', width: 110, sortable: true, styler: fontStyler},
                {field: 'RefferenceUserID', title: 'Reference ID', width: 90, sortable: true, styler: fontStyler},
                {field: 'RefferenceTypeName', title: 'Reference Type', width: 100, sortable: true, styler: fontStyler},
                {field: 'ApplicationComment', title: 'Comment', width: 120, sortable: true, styler: function() {
                        return 'word-wrap: break-word;font-size:14px;';
                    }},
                {field: 'ApplicationStateID', title: 'Status', width: 100, sortable: true, styler: fontStyler},
                {field: 'FirstCreatedTime', title: 'Date Created', width: 90, sortable: true, styler: fontStyler},
                {field: 'ElapsedDay', title: 'ElapsedDay', width: 70, sortable: true, styler: conditionStyler},
                {field: 'Action', title: 'Action', width: 110, formatter: rowFormatter}
            ]];
        // handle data
        var toArrayData = function(carriedData) {
            var rows = [];
            for (var i = 0; i < carriedData.length; i++) {
                rows.push({
                    ApplicationId: carriedData[i].ApplicationId,
                    ApplicationTypeID: carriedData[i].ApplicationTypeID,
                    ApplicationTypeName: carriedData[i].ApplicationTypeName,
                    RefferenceUserName: carriedData[i].RefferenceUserName,
                    RefferenceUserID: carriedData[i].RefferenceUserID,
                    RefferenceTypeID: carriedData[i].RefferenceTypeID,
                    RefferenceTypeName: carriedData[i].RefferenceTypeName,
                    ApplicationComment: carriedData[i].ApplicationComment,
                    LatestComment: carriedData[i].LatestComment,
                    ApplicationStateID: carriedData[i].ApplicationStateID,
                    HandleSchoolID: carriedData[i].HandleSchoolID,
                    HandleSchoolName: carriedData[i].HandleSchoolName,
                    SecretaryID: carriedData[i].SecretaryID,
                    SecretaryName: carriedData[i].SecretaryName,
                    SecretaryEmail: carriedData[i].SecretaryEmail,
                    AdvisorID: carriedData[i].AdvisorID,
                    AdvisorName: carriedData[i].AdvisorName,
                    AdvisorEmail: carriedData[i].AdvisorEmail,
                    ActionUserID: carriedData[i].ActionUserID,
                    ActionUserName: carriedData[i].ActionUserName,
                    ActionUserEmail: carriedData[i].ActionUserEmail,
                    SortIndex: carriedData[i].SortIndex,
                    LastUpdateTime: carriedData[i].LastUpdateTime,
                    FirstCreatedTime: carriedData[i].FirstCreatedTime,
                    ElapsedDay: carriedData[i].ElapsedDay
                });
            }
            return rows;
        };

        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        var fm = function(rowIndex, rowData) {
            var html = "<div id =\"Form_TableGridDetailView_{0}\"></div>";
            return String.format(html, rowIndex);
        };

        var detailViewEventhandler = function(rowIndex, rowData) {
            CPS.sendRequestToServer("CPS_QueryFileList", [rowData.ApplicationId, rowData.HandleSchoolID], function(objData) {
                var counter = 1;
                var fileTableHtml = "<table><th>File Index</th><th colspan =\"2\">File Name</th><th>Upload User</th><th>Upload Time</th>";
                for (var id in objData.Response_CarriedData) {
                    var FileID = objData.Response_CarriedData[id].FileID;
                    var FileName = objData.Response_CarriedData[id].FileName;
                    var UserName = objData.Response_CarriedData[id].UserName;
                    var UserEmail = objData.Response_CarriedData[id].UserEmail;
                    var FileUploadTime = objData.Response_CarriedData[id].FileUploadTime;
                    //FileDownload
                    fileTableHtml += "<tr><td style = 'text-align:center'>{0}</td><td colspan =\"2\">"; // [0] counter index
                    // [1] fileID [2]=SID [3]= File Name 
                    fileTableHtml += "<a target='_blank' href=\"../Server/server.php?ActionName=FileDownload&FileID={1}&SID={2}\">{3}</a></td>";
                    fileTableHtml = String.format(fileTableHtml, counter, FileID, CPS.getSessionID(), FileName);
                    //[4] userName [5] Upload Time
                    var nameHtml = "<td><a href = 'javascript:void(0);'onclick = 'Mailer.Application_SendEmailByClickingName(\"{0}\",\"{1}\",\"{2}\",\"{3}\");'>";
                    fileTableHtml += String.format(nameHtml, UserName, UserEmail, CPS.getUserName(), CPS.getUserEmail());
                    fileTableHtml += "{0}</a></td><td>{1}</td></tr>";
                    //fileTableHtml = String.format(fileTableHtml, FileID, FileName, UserName, Role, counter, CPS.getSessionID());
                    fileTableHtml = String.format(fileTableHtml, UserName, FileUploadTime);
                    counter += 1;
                }

                fileTableHtml += "</table>";
                var html = " <table class = \"detailviewTable\" style =\"border:1px solid #369\"><tr><th>From:</th>";
                var fromHtml = "<td><a href = 'javascript:void(0);'onclick = 'Mailer.Application_SendEmailByClickingName(\"{0}\",\"{1}\",\"{2}\",\"{3}\");'>";
                html += String.format(fromHtml, rowData.ActionUserName, rowData.ActionUserEmail, CPS.getUserName(), CPS.getUserEmail());
                html += "{0}</a></td><th>Last updated time:</th><td>{1}</td></tr><tr><th>Last comment:</th>";
                html += "<td colspan=\"3\">{2}</td></tr><tr><th>Secretary:</th>";
                html = String.format(html, rowData.ActionUserName, rowData.LastUpdateTime, rowData.LatestComment);
                var secretaryHtml = "<td><a href = 'javascript:void(0);'onclick = 'Mailer.Application_SendEmailByClickingName(\"{0}\",\"{1}\",\"{2}\",\"{3}\");'>";
                html += String.format(secretaryHtml, rowData.SecretaryName, rowData.SecretaryEmail, CPS.getUserName(), CPS.getUserEmail());
                html += "{0}</a></td><th>Advisor:</th>";
                html = String.format(html, rowData.SecretaryName);
                var advisorHtml = "<td><a href = 'javascript:void(0);'onclick = 'Mailer.Application_SendEmailByClickingName(\"{0}\",\"{1}\",\"{2}\",\"{3}\");'>";
                html += String.format(advisorHtml, rowData.AdvisorName, rowData.AdvisorEmail, CPS.getUserName(), CPS.getUserEmail());
                html += "{0}</a></td></tr><tr><th>School:</th><td colspan = \"2\">{1}</td>";
                html = String.format(html, rowData.AdvisorName, rowData.HandleSchoolName);
                var HistoryBtn = "<td style='text-align:right'><button id='viewDetailBtn' onClick ='currentController.Application_Item_ViewHistory(\"{0}\",\"{1}\");'>View history</button></td></tr><tr>";
                html += String.format(HistoryBtn, rowData.ApplicationId, rowData.HandleSchoolID);
                html += "<td colspan = \"4\" class = \"fileTH\" style='text-align: center;padding-left: 50px'><div id = \"TableGrid_UploadFileList\" style = 'overflow-y: scroll; max-height: 250px'>{0}</div></td></tr></table>";
                html = String.format(html, fileTableHtml);
                var expandSelector = String.format("{0} #Form_TableGridDetailView_{1}", panelSelector, rowIndex);
                $(expandSelector).panel({
                    content: html
                });
            });
        };

        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        CPS.sendRequestToServer("Secretaty_QuerySummaryDetail", [schoolID, appTypeId], function(data) {
            Trace.debugJsObjectData(data.Response_CarriedData, "#777");
            DataGridComponent.Init(panelSelector, header);
            DataGridComponent.SetDetailviewWithExpandEvent(fm, detailViewEventhandler);
            DataGridComponent.LoadData(toArrayData(data.Response_CarriedData));
            CPS.CloseProcessing(function() {

            });
        });
    };

//-----------------------------------------------------------------------------------------------
// The below is the button action of eath application Item
//-----------------------------------------------------------------------------------------------

    this.Application_Item_ViewHistory = function(rowApplicationID, rowHandleSchoolID) {
        var ActionListHtmlFormatter = function(dataAL) {
            var ObjAL = dataAL.Response_CarriedData;

            var counter = 1;
            var ActionListHtml = "<table id ='HistoryDetailTable'><tr><th>Index</th><th>Action</th><th>Action User</th><th>Date</th><th colspan=\"2\">Comment</th></tr>";
            // build the list
            var ObjAL = dataAL.Response_CarriedData;
            for (var id in ObjAL) {
                var ActionUserName = ObjAL[id].ActionUserName;
                var StateID = ObjAL[id].NewStateID;
                var date = ObjAL[id].CreatedTime;
                var Comment = ObjAL[id].NewStateComment;

                ActionListHtml += "<tr onmouseover=\"this.style.backgroundColor='#b5cfd2';\" onmouseout=\"this.style.backgroundColor='#ffffff';\">";
                ActionListHtml += "<td style = 'text-align:center'>{0}</td><td>{1}</td><td>{2}</td>";
                ActionListHtml += "<td>{3}</td><td colspan = \"2\" style='text-align:left;'>{4}</td></tr>";
                ActionListHtml = String.format(ActionListHtml, counter, StateID, ActionUserName, date, Comment);
                counter += 1;
            }
            ActionListHtml += "</table>";
            return ActionListHtml;
        };

        CPS.sendRequestToServer("CPS_searchApplicationActionList", [rowApplicationID, rowHandleSchoolID], function(dataAL) {
            Trace.debugJsObjectData(dataAL.Response_CarriedData, "#369");
            var ActionList_Html = ActionListHtmlFormatter(dataAL);

            var tempDivSelector = "#" + CPS.AddTempDIV();
            CPS.ShowAsWindow(tempDivSelector, 600, 350, true);
            $(tempDivSelector).panel({
                title: "Application History Detail",
                content: ActionList_Html
            });

        });
    };
    this.Application_Item_Accept = function(rowApplicationID, rowHandleSchoolID, rowStateID, rowActionUserID, strCallbackAction) {
        CPS.confirmAction("Accept Confirmation", "confirm to Accept this Application?", function() {
            var acceptEntity = new Action_Entity();
            acceptEntity.rowApplicationID = rowApplicationID;
            acceptEntity.rowHandleSchoolID = rowHandleSchoolID;
            acceptEntity.rowStateID = rowStateID;
            acceptEntity.rowActionUserID = rowActionUserID;
            acceptEntity.newActionUserID = CPS.getUserID();
            acceptEntity.newActionStateID = "S01";
            acceptEntity.callbackAction = strCallbackAction;
            //Send to Server
            CPS.sendRequestToServer("Secretaty_AcceptApplication", acceptEntity, function(data) {
                CPS.parseActionString(data.Response_ActionName);
                CPS.showNotification("Sucess", "The application has been accepted");
            });
        });
    };


    this.Application_Item_Assign = function(rowApplicationID, rowHandleSchoolID, rowStateID, rowActionUserID, strCallbackAction) {
        CPS.sendRequestToServer("Secretaty_GetAdevisorList", [CPS.getSchoolID()], function(data) {
            var tempDivSelector = "#" + CPS.AddTempDIV();
            var html = "<table><tr><td>choose Advisor</td><td><input type=\"text\" id=\"Advisor_Combobox\"/></td></tr>";
            html += "<tr><td>Comments for Advisor</td><td><textarea id='Comment_To_Advisor'></textarea></td></tr>";
            html += "<tr><td colspan='2' style=\"text-align: center\">";
            html += "<a href='javascript:void(0)'class='easyui-linkbutton' id='Btn_Assign'>Assign</a></td></tr></table>";
            // show the pop Dialogue
            CPS.ShowAsWindow(tempDivSelector, 350, 150, true);
            $(tempDivSelector).panel({content: html});

            var comboSelector = String.format("{0} {1}", tempDivSelector, "#Advisor_Combobox");
            $(comboSelector).combobox({
                required: true,
                editable: false,
                valueField: 'UserID',
                textField: 'UserName',
                onBeforeLoad: function()
                {
                    $(comboSelector).combobox('loadData', data.Response_CarriedData);
                }
            });
            // the comment
            var commentSelector = String.format("{0} {1}", tempDivSelector, "#Comment_To_Advisor");
            // regester the submit fucntion
            $(commentSelector).validatebox({
                required: true
            });

            // submit button
            var assignSelector = String.format("{0} {1}", tempDivSelector, "#Btn_Assign");
            // handle the click fucnction
            $(assignSelector).click(function() {
                // validation
                if (!$(comboSelector).combobox('isValid'))
                {
                    CPS.showNotification("ERROR", "Must Select an advisor to continute to handle application.");
                    return;
                }

                if (!$(commentSelector).validatebox('isValid'))
                {
                    CPS.showNotification("ERROR", "Must input comments for advisor");
                    return;
                }

                CPS.confirmAction("confirmation", "confirm to Assign this Advisor?", function() {
                    // Submit the data to Server
                    var assignEntity = new Action_Entity();
                    assignEntity.rowApplicationID = rowApplicationID;
                    assignEntity.rowHandleSchoolID = rowHandleSchoolID;
                    assignEntity.rowStateID = rowStateID;
                    assignEntity.rowActionUserID = rowActionUserID;
                    assignEntity.newActionUserID = CPS.getUserID();
                    assignEntity.newActionStateID = "S03";
                    assignEntity.newActionCommnet = $(commentSelector).val();
                    assignEntity.newAdvisorID = $(comboSelector).combobox('getValue');

                    assignEntity.callbackAction = strCallbackAction;
                    // send the request to the server
                    CPS.sendRequestToServer("Secretaty_AssignAdvisor", assignEntity, function(data) {
                        $(tempDivSelector).window('close');
                        CPS.parseActionString(data.Response_ActionName);
                        CPS.showNotification("Sucess", "Addvisor has been assigned");
                    });
                });
            });
        });

    };





}